import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/server/api/other_api.dart';
import 'package:sports_new/utils/app_config.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/widgets/share/share_image.dart';
import 'package:sports_new/widgets/share/share_pic_sheet.dart';
import 'package:tencent_kit/tencent_kit.dart';
import 'package:weibo_kit/weibo_kit_platform_interface.dart';
import '../../resources/colours.dart';
import '../../utils/toast_utils.dart';
import '../../utils/user.dart';
import '../../utils/utils.dart';
import '../base/qkd_text.dart';

class ShareEntity{
  String? title;
  String? content;
  String? url;
  String? logo;
  String? show;
  bool? needChannel;
  Widget? imageWidget;
  Function()? onTap;

  ShareEntity({
    this.title = '分享给你一个看比赛和数据的APP',
    this.content = '球客岛，专业体育比分预测平台',
    this.url,
    this.logo,
    this.imageWidget,
    this.needChannel = false,
    this.onTap});

  ShareEntity.fromJson(Map<String, dynamic> json) {
    title = json['title'] ?? '分享给你一个看比赛和数据的APP';
    content = json['content'] ?? '球客岛，专业体育比分预测平台';
    url = json['url'];
    logo = json['logo'];
  }
}

class ShareSheet extends StatefulWidget {
  const ShareSheet({super.key, this.append, this.fromLive = false});

  final Widget? append;
  final bool fromLive;

  @override
  State<ShareSheet> createState() => _ShareSheetState();
}

class _ShareSheetState extends State<ShareSheet> {
  String logo = 'https://oss.qiuxiangbiao.com/prod/resource/qkd_logo.png';
  late List images = [
    'share_wx.png',
    'share_timeline.png',
    'share_qq.png',
    'share_qqzone.png',
    'share_wb.png',
    'share_clipboard.png'
  ];
  List titles = [
    '微信',
    '朋友圈',
    'QQ',
    'QQ空间',
    '微博',
    '复制链接'];
  late Uint8List thumbImage;
  String url = SpUtils.baseUrl.contains("test")?"http://testm.qiuxiangbiao.cc/":"https://m.qiukedao.net/";
  ShareEntity? data;
  List<Function()> tapList = [];

  @override
  void initState() {
    formData();
    super.initState();
  }

  Future formData() async{
    if(Get.arguments is ShareEntity){
      data = Get.arguments;
    }else if(Get.arguments is Json){
      data = ShareEntity.fromJson(Get.arguments);
    }else if(Get.arguments is String){
      data = ShareEntity.fromJson(jsonDecode(Get.arguments));
    }
    if(data?.imageWidget != null){
      images = [
        "share_img.png",
        'share_wx.png',
        'share_timeline.png',
        'share_qq.png',
        'share_qqzone.png',
        'share_wb.png',
        'share_clipboard.png'
      ];
      titles = [
        "生成图片",
        '微信',
        '朋友圈',
        'QQ',
        'QQ空间',
        '微博',
        '复制链接'
      ];
    }
    List<ResourceEntity>? urlInfo = await OtherApi.getAppList("app_page_share");
    String? rootUrl = urlInfo?.firstWhere((element) => element.button == (widget.fromLive?"live_share_url":"root")).content;
    String? channel = urlInfo?.firstWhere((element) => element.button == "channel").content;
    if(rootUrl != null){
      url = rootUrl;
    }
    ByteData bytes =
    await rootBundle.load(Utils.getImgPath('qkd_logo.png'));
    if(data?.logo != null){
      bytes = await NetworkAssetBundle(Uri.parse(data!.logo!)).load(data!.logo!);
    }
    thumbImage = bytes.buffer.asUint8List();
    if(RegExp("^http[s]?://").hasMatch(data?.url ?? "")){
      url = data!.url!.replaceFirst("UserId", "${User.info?.id}").replaceFirst("Token", "${User.auth?.token}");
    }else{
      url = "$url${data?.url ?? ""}${data?.needChannel == true?"&qd=$channel":""}".replaceFirst("UserId", "${User.info?.id}").replaceFirst("Token", "${User.auth?.token}");
    }
    tapList = [
      if(data?.imageWidget != null)
      () => Get.bottomSheet(
        SharePicSheet(widget: data!.imageWidget!),
        isScrollControlled: true
      ),
      () => Fluwx().share(
        WeChatShareWebPageModel(url,
          scene: WeChatScene.session,
          title: data?.title ?? "",
          description: data?.content,
          thumbnail: WeChatImage.binary(thumbImage)
        )
      ),
      () => Fluwx().share(
        WeChatShareWebPageModel(url,
          scene: WeChatScene.timeline,
          title: data?.title ?? "",
          description: data?.content,
          thumbnail: WeChatImage.binary(thumbImage)
        )
      ),
      () => TencentKitPlatform.instance.shareWebpage(
        scene: TencentScene.kScene_QQ,
        title: data?.title ?? "",
        summary: data?.content,
        appName: '球客岛',
        imageUri: Uri.parse(data?.logo ?? logo),
        targetUrl: url),
      () => TencentKitPlatform.instance.shareWebpage(
        scene: TencentScene.kScene_QZone,
        title: data?.title ?? "",
        summary: data?.content,
        appName: '球客岛',
        imageUri: Uri.parse(data?.logo ?? logo),
        targetUrl: url),
      () => WeiboKitPlatform.instance.shareWebpage(
        title: data?.title ?? "",
        description: data?.content ?? "",
        thumbData: thumbImage,
        webpageUrl: url),
      () => Clipboard.setData(ClipboardData(text: url))
        .then((value) => ToastUtils.show("已复制分享链接"))
    ];
    List<int> list = [1,1,1,1,1];
    if(data?.show != null) {
      list = data!.show!.split("").map((e) => e.toInt()!).toList();
      for (var i = 0; i < list.length; i++) {
        if (list[i] == 0) {
          titles.removeAt(i);
          images.removeAt(i);
          tapList.removeAt(i);
        }
      }
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return BottomSheet(
      enableDrag: false,
      clipBehavior: Clip.hardEdge,
      shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(10), topRight: Radius.circular(10))),
      onClosing: () {},
      builder: (context) {
        return Container(
          color: Colours.greyFD,
          child: SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const SizedBox(height: 14),
                const QkdText(
                  '分享至',
                  color: Colours.grey99
                ),
                const SizedBox(height: 20),
                if(titles.length <=4)...[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: List.generate(titles.length, (index) => item(index))
                  )
                ]else...[
                  SizedBox(
                    height: 71,
                    child: ScrollConfiguration(
                      behavior: const ScrollBehavior().copyWith(overscroll: false),
                      child: ListView(
                        shrinkWrap: true,
                        padding: const EdgeInsets.only(left: 16),
                        scrollDirection: Axis.horizontal,
                        children: List<Widget>.generate(
                          titles.length, (index) => item(index)
                        ).insertEvery(Container(width: 16))
                      )
                    )
                  )
                ],
                const SizedBox(height: 24),
                widget.append ?? Container(),
                Container(
                  height: 10,
                  width: double.infinity,
                  color: Colours.greyF7,
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    navigator?.pop();
                  },
                  child: Container(
                    height: 52,
                    color: Colours.greyFD,
                    child: const Center(
                      child: QkdText('取消',
                        fontSize: 17, color: Colours.grey99
                      )
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  item(int index) {
    return GestureDetector(
      onTap: () {
       data?.onTap?.call();
       navigator?.pop();
       tapList[index].call();
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset(Utils.getImgPath(images[index]), width: 50,height: 50),
          const SizedBox(height: 4),
          QkdText(
            titles[index],
            fontSize: 12,
            color: Colours.grey99
          )
        ]
      ),
    );
  }
}
